package com.ruoyi.web.controller.deepSeek;

import com.google.gson.Gson;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

public class OllamaChat {
    public static void main(String[] args) {
        try {
            // 创建 HttpClient 实例
            HttpClient client = HttpClients.createDefault();

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-r1:1.5b");

            // 设置用户消息
            Map<String, String> userMessage1 = new HashMap<>();
            userMessage1.put("role", "user");
            userMessage1.put("content", "你是一个图表专家");

            Map<String, String> userMessage2 = new HashMap<>();
            userMessage2.put("role", "user");
            userMessage2.put("content", "你叫什么");

            requestBody.put("messages", new Map[]{userMessage1, userMessage2});

            // 使用 Gson 转换为 JSON 格式
            Gson gson = new Gson();
            String jsonBody = gson.toJson(requestBody);

            // 创建 HTTP POST 请求
            HttpPost postRequest = new HttpPost("http://localhost:11434/chat");
            postRequest.setHeader("Content-Type", "application/json");
            postRequest.setEntity(new StringEntity(jsonBody));

            // 执行请求并获取响应
            HttpResponse response = client.execute(postRequest);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder responseBody = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseBody.append(line);
            }

            // 打印响应内容
            System.out.println("Response Body: " + responseBody.toString());

            // 使用 Gson 将响应 JSON 转换为 Map
            String jsonResponse = responseBody.toString();
            Map<String, Object> responseMap = gson.fromJson(jsonResponse, Map.class);

            // 打印响应 Map 的内容
            System.out.println("Response as Map: " + responseMap);

            // 如果你需要访问特定字段，可以像这样获取
            Map<String, Object> message = (Map<String, Object>) responseMap.get("message");
            System.out.println("Message content: " + message.get("content"));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
